﻿@{
    ViewBag.Title = "FormDataAction";
}
@section HeaderContent{
    <script type="text/javascript">
        if (typeof FileReader == undefined) {
            alert("您的浏览器不支持FileReader！");
        }
        function upload() {
            var file = document.getElementById("file").files;
            var fileController = '@Url.Action("SaveFileAjax", "Home")';
            //FormData
            var form = new FormData();
            form.append("author", "kid");
            for (var i = 0; i < file.length; i++) {
                form.append("file", file[i]);
            }
            //XMLHttpRequest
            var xhr = new XMLHttpRequest();
            xhr.open("post", fileController, true);
            xhr.onload = function (result) {
                console.log("上传成功");
            }
            xhr.upload.addEventListener("progress", progressFunction, false);
            xhr.send(form);
        }
        function progressFunction(evt) {
            var progressBar = document.getElementById("progressBar");
            var percentageDiv = document.getElementById("percentage");
            if (evt.lengthComputable) {
                progressBar.max = evt.total;
                progressBar.value = evt.loaded;
                percentageDiv.innerHTML = Math.round(evt.loaded / evt.total * 100) + "%";
            }
        }
        function showFileInfo() {
            var files = document.getElementById("file").files;
            for (var i = 0; i < files.length; i++) {
                var file = files[i];
                if (!(/image\/\w+/.test(file.type))) {
                    $("#fileInfo").append("<span>type:" + file.type + "--******非图片类型*****--name:" + file.name + "--size:" + file.size + "</span><br />");
                }
                else {
                    $("#fileInfo").append("<span>type:" + file.type + "--name:" + file.name + "--size:" + file.size + "</span><br />");
                    var reader = new FileReader();
                    reader.readAsDataURL(file); //读取文件的编码"gb2312"，readAsBinaryString：异步方式，不会影响主线程
                    reader.onload = function (e) {
                        var urlData = this.result;
                        $("#fileInfo").append("<img width='100' src='" + urlData + "' alt='" + file.name + "' />");
                    }
                }
            }
        }
    </script>
}
<h2>
    使用FormData和XMLHttpRequest，完成异步多文件上传功能</h2>
<input type="file" multiple="multiple" id="file" onchange="showFileInfo()" />
<input type="button" value="上传" onclick="upload()" />
<progress id="progressBar" value="0" max="100">
</progress>
<span id="percentage"></span>
<br />
<div id="fileInfo">
</div>
